package team.fourth.combat.web;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import team.fourth.combat.commen.constant.RedisConstant;
import team.fourth.combat.commen.entity.PageResult;
import team.fourth.combat.commen.entity.QueryPageBean;
import team.fourth.combat.commen.entity.Result;
import team.fourth.combat.commen.utils.QiniuUtils;
import team.fourth.combat.commen.utils.RedisUtil;
import team.fourth.combat.pojo.Setmeal;
import team.fourth.combat.service.SetmealService;

import java.io.IOException;

@RequestMapping("/setmeal")
@RestController
public class SetmealController {

    @Reference
    SetmealService setmealService;
    @Autowired
    RedisUtil redisUtil;

    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        try {
            //修改文件名称
            String originalFilename = imgFile.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(i);
            String newFileName = UUID.randomUUID().toString() + suffix;
            //调用七牛sdk上传
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),newFileName);
            //把图片名称返回（页面要拼接域名）

            redisUtil.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newFileName);
            return Result.success("图片上传成功",newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            //公司里面需要把错误信息收集起来，要分析解决（ELK）
            return Result.error("图片上传失败");
        }
    }

    public static void main(String[] args) {
        String name = "sadhasjdkdsf13213123aksdnffdg.dsjdjglfdgispfd%%###!!.jpeg";

        //找到最后一个  点儿 的位置
        int i = name.lastIndexOf(".");

        String suffix = name.substring(i);

        System.out.println(suffix);
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal){
       setmealService.add(setmeal);
       redisUtil.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
       return Result.success("");
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.findPage(queryPageBean);
    }

}
